import {Injectable, OnInit, OnDestroy, DoCheck, OnChanges, SimpleChanges} from '@angular/core';
import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {ResponseModel} from './ResponseModel';
import {Account} from './login/Account';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json;charset=utf-8', 'X-Requested-With': 'XMLHttpRequest',}),
};
@Injectable()
export class UserService {
  authenticated;
  constructor(private http: HttpClient) {
  }
  getUserData(): Observable<any> {
    console.log(this.authenticated);
    return this.http.get<any>('/api/getUserData');
  }

  isLogin():boolean {
    let obj = localStorage.getItem("access_token");
    if(typeof obj == "undefined" || obj == null || obj == "")
      return false;
    else
      return true;
  }

  login(credentials,callback,failureHandlerCallback) {
    this.http.post<ResponseModel<Account>>('/user/login',credentials,{
      headers: new HttpHeaders({'Content-Type': 'application/json;charset=utf-8', 'X-Requested-With': 'XMLHttpRequest',}),
      observe: 'response',
    }).subscribe(response=>{
      let token = response.headers.get("token");
      let body: ResponseModel<Account> = response.body;
      let userInfo: Account = body.data;
      localStorage.setItem("access_token",token);
      localStorage.setItem("user_info",JSON.stringify(userInfo));

      if (body.code === 'SUCCESS') {
        this.authenticated = true;
        callback && callback();
      } else {
        this.authenticated = false;
        failureHandlerCallback && failureHandlerCallback();
      }
    });
  }
}
